package com.hpq.user.service.impl;

import com.hpq.common.constant.RedisConstant;
import com.hpq.common.utils.JwtUtils;
import com.hpq.common.utils.RedisUtils;
import com.hpq.user.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    public static final int TOKEN_EXPIRE_DAYS = 3;
    public static final int RENEWAL_TOKEN_DAYS = 1;
    @Autowired
   private JwtUtils jwtUtils;

    /**
     * 更新token有效期
     * @param token
     */
    @Override
    @Async
    public void refreshToken(String token) {
        //得到用户uid
        Long uid = getValidUid(token);
        //获取token的键
        String tokenKey = getTokenKey(uid);
        //获取过期时间
        Long expire = RedisUtils.getExpire(tokenKey, TimeUnit.DAYS);
        if(expire < RENEWAL_TOKEN_DAYS){
            RedisUtils.set(getTokenKey(uid), token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        }
        if(expire == -2){
            return;
        }
    }

    /**
     * 登录成功，获取token
     * @param uid
     * @return
     */
    @Override
    public String login(Long uid) {
        // 生成token
        String token = jwtUtils.createToken(uid);
        //存储到redis,并设置过期时间
        RedisUtils.set(getTokenKey(uid), token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        return token;
    }

    /**
     * 如果token有效，返回uid
     * @param token
     * @return
     */
    @Override
    public Long getValidUid(String token) {
        Long uid = jwtUtils.getUidByToken(token);
        if(Objects.isNull(uid)){
            return null;
        }
        String oldToken  = RedisUtils.getStr(getTokenKey(uid));
        if(StringUtils.isBlank(oldToken)){
            return null;
        }
        return Objects.equals(oldToken, token) ? uid : null;
    }

    /**
     * 获取token的键
     * @param uid
     * @return
     */
    private String getTokenKey(Long uid){
        return RedisConstant.getKey(RedisConstant.USER_TOKEN_KEY,uid);
    }
}
